package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private String key;
    private StringRedisTemplate stringRedisTemplate;
    // 获取UUID并去除中间的-
    private static final String UUID_PREFIX = UUID.randomUUID().toString(true);

    private static final String KEY_PREFIX = "lock:";

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String key, StringRedisTemplate stringRedisTemplate) {
        this.key = key;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long expireTime) {
        long threadId = Thread.currentThread().getId();
        // 锁不存在则设置
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + key, UUID_PREFIX + threadId, expireTime, TimeUnit.SECONDS);
        // Boolean返回boolean会拆箱，有可能出现空指针异常，所以手动转换成boolean返回
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        // 拿到锁的value标识 与 当前标识进行对比 相同才能删除
        // String value = stringRedisTemplate.opsForValue().get(KEY_PREFIX + key);
        // if (value != null && value.equals(UUID_PREFIX + Thread.currentThread().getId())) {
        //     stringRedisTemplate.delete(KEY_PREFIX + key);
        // }

        // 执行lua脚本 脚本路径 key列表 其它参数
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(KEY_PREFIX + key), UUID_PREFIX + Thread.currentThread().getId());
    }
}
